<style lang="scss" scoped>
.container {
  padding: 16px;
  border: 1px solid #efefef;
  /* // .upload-demo{
	// 	width: 150px;
	// 	.el-upload {
	// 		display: inline-block;
	// 		text-align: center;
	// 		cursor: pointer;
	// 		outline: none;
	// 	}
	// } */
}

.el-select .el-select--small {
  display: block !important;
}
.el-upload,
.el-upload-dragger {
  height: 40px !important;
}
</style>

<!-- 页面布局-->
<template>
  <div class="table">
    <!-- 主体区 -->
    <div class="container">
      <!-- 表单区 -->
      <div class="form-data-box">
        <el-form
          :model="formBean"
          :rules="validateRules"
          ref="form1"
          label-width="120px"
          class="ruleForm"
          style="width: 80%"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="卡片版面描述" prop="faceName">
                <el-input
                  :readonly="readOnly"
                  v-model="formBean.faceName"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="运营商" prop="isp">
                <el-select :disabled="readOnly" v-model="formBean.isp">
                  <el-option
                    v-for="item in dicts.isp"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="上传图片" prop="fileName">
                <div class="fxrow">
                  <el-input
                    :readonly="readOnly"
                    v-model="formBean.fileName"
                  ></el-input>
                  <el-upload
                    style="height: 30px"
                    class="upload-demo1111"
                    action="/cardFace/"
                    :before-upload="beforeupload"
                    multiple
                    :limit="1"
                    :show-file-list="false"
                    accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PBG"
                  >
                    <el-button
                      size="small"
                      type="primary"
                      style="vertical-align: top"
                      @click="clearUpload"
                      :disabled="readOnly"
                      >点击上传</el-button
                    >
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="图片预览">
                <div class="demo-image__preview">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="url"
                    :preview-src-list="srcList"
                  >
                  </el-image>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 表单区END -->
      <!-- 按钮操作区 -->
      <span slot="footer" class="form-btn-box">
        <el-button v-if="!readOnly" @click="resetForm('form1')"
          >重 置</el-button
        >
        <el-button
          v-if="!readOnly"
          type="primary"
          @click="submitForm()"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确 定</el-button
        >
        <el-button @click="cnacelForm('form1')">取 消</el-button>
      </span>
      <!-- 按钮操作区END -->
    </div>
    <!-- 主体区END -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 提交表单的loading设置标识
      fullscreenLoading: false,
      firstLoadedData: "{}",
      // 新增用户表单信息
      formBean: {
        faceName: "", //卡片版面描述
        fileName: "", //上传图片
        isp: "", //运营商
      },
      url: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
      srcList: [
        "https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg",
        "https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg",
      ],
      orgNotsele: true,
      // 表单校验规则
      validateRules: {
        faceName: [
          { required: true, message: "请输入卡片版面描述", trigger: "blur" },
          {
            max: 100,
            min: 1,
            message: "长度须符合 1 ~ 100 个字符",
            trigger: "blur",
          },
        ],
        fileName: [{ required: true, message: "请上传图片", trigger: "blur" }],
        isp: [{ required: true, message: "请选择运营商", trigger: "blur" }],
      },
      //所选记录id
      selectedId: "",
      //事物类型
      actType: "",
      // 表单只读状态
      readOnly: false,
      readOnlyEdt: false,
      //字典集
      dicts: {},
      cascaders: {},
      cascaderSelected: {},
      updimgurl: "",
      file: null,
    };
  },
  props: {
    sourceData: {
      required: true,
    },
  },
  // 进入页面加载数据
  mounted() {
    this.handleInitLoad();
  },
  methods: {
    /**
     * 组件初始化加载
     */
    handleInitLoad() {
      this.initSelectOptoins();
      this.initFormData();
    },

    /**
     * 初始加载字典选项
     */
    initSelectOptoins() {
      this.loadSelectOptoins("isp", null);
    },

    /**
     * 通用定义:下拉字典
     *  @augments dictKind 字典类型
     */
    loadSelectOptoins(dictKind, params) {
      let url = "/bill/dictionary/";
      this.$axios
        .get(url, {
          params: {
            type: dictKind,
          },
          headers: {
            operator: this.$util.getLoginer().userid,
            withCredentials: true,
          },
        })
        .then((res) => {
          let data = res.data;
          if (data.success) {
            this.$set(this.dicts, dictKind, data.data.list);
          } else {
            console.log(data.message);
            // this.$error( "查询失败" + data.message );
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    /**
     * 取消返回
     * @augments formName 表单名称
     */
    cnacelForm(formName) {
      this.$refs[formName].resetFields();
      this.$emit("cancel", this.cancelData);
    },
    /**
     * 重置表单
     * @augments formName 表单名称
     */
    resetForm(formName) {
      this.formBean = JSON.parse(this.firstLoadedData);
    },
    /**
     *初始化加载表单数据
     */
    initFormData() {
      this.selectedId = this.sourceData.seleid;
      this.actType = this.sourceData.actType;
      this.readOnlyEdt = true;
      if (this.actType == "view") {
        // 查看状态 标识表单只读
        this.readOnly = true;
      } else if (this.actType == "add") {
        this.readOnly = false;
        this.readOnlyEdt = false;
        //清空修改保存之后数据还存在的情况
        for (var key in this.formBean) {
          this.formBean[key] = "";
        }
      } else {
        this.readOnly = false;
      }
      if (this.$util.getLoginer().administrator == true) {
        this.orgNotsele = false;
      } else {
        this.orgNotsele = true;
      }
      var url = "/bill/cardFace/";
      if (
        this.actType != null &&
        (this.actType == "upd" || this.actType == "view")
      ) {
        url += this.selectedId + "/";
        this.$axios
          .get(url, {
            params: {},
            headers: {
              operator: this.$util.getLoginer().userid,
              withCredentials: true,
            },
          })
          .then((res) => {
            let data = res.data;
            if (data.success) {
              this.formBean = data.data;
              if (null == this.formBean.ispName || "" == this.formBean.ispName)
                this.formBean.isp = "";
              this.firstLoadedData = JSON.stringify(this.formBean);
            } else {
              this.$error(data.message);
            }
          })
          .catch((err) => {});
      }
    },

    beforeupload(file) {
      this.file = file;
      this.$set(this.formBean, "fileName", file.name);
      return false;
    },

    clearUpload() {
      console.log("clearUpload");
      this.$set(this.formBean, "fileName", "");
      this.file = null;
    },

    /**
     * 提交表单
     * @augments formName 表单名称
     */
    submitForm(e) {
      //
      this.$refs["form1"].validate((valid) => {
        if (valid) {
          let uploadForm = new FormData();
          uploadForm.append("file", this.file);
          uploadForm.append("json", JSON.stringify(this.formBean));
          // 表单校验成功
          if (this.actType == "upd") {
            //
            // 开启提交表单的loading
            this.fullscreenLoading = true;
            var url =
              "/bill/cardFace/" +
              this.selectedId +
              "/?time=" +
              new Date().getTime();
            this.$axios
              .put(url, uploadForm, {
                headers: {
                  operator: this.$util.getLoginer().userid,
                  withCredentials: true,
                },
              })
              .then((res) => {
                let data = res.data;
                // 关闭提交表单的loading
                this.fullscreenLoading = false;
                if (data.success) {
                  this.$message({
                    message: "数据保存成功.",
                    type: "success",
                  });
                  this.$emit("ok", {});
                } else {
                  this.$error(data.message);
                }
              })
              .catch((err) => {
                this.fullscreenLoading = false;
              });
          } else if (this.actType == "add") {
            var url = "/bill/cardFace/?time=" + new Date().getTime();
            //
            // 开启提交表单的loading
            this.fullscreenLoading = true;
            this.$axios
              .post(url, uploadForm, {
                headers: {
                  operator: this.$util.getLoginer().userid,
                  withCredentials: true,
                },
              })
              .then((res) => {
                let data = res.data;
                // 关闭提交表单的loading
                this.fullscreenLoading = false;
                if (data.success) {
                  this.$message({
                    message: "数据保存成功.",
                    type: "success",
                  });
                  this.$emit("ok", {});
                } else {
                  this.$error(data.message);
                }
              })
              .catch((err) => {
                this.fullscreenLoading = false;
              });
          }
        } else {
          // 表单校验失败
          // this.$error("数据校验失败.");
        }
      });
    },
  },
};
</script>
